<template>
	<!-- 聊天界面展示https://www.bilibili.com/video/BV1hT4y1P75N?p=22  搭建1和2 -->
	<view class="content" @touchmove="touchstart">

		<scroll-view id="chat" class="chat" scroll-y="true" scroll-with-animation="true"
			:scroll-into-view="scrollToView" :style="{paddingBottom:keyboardHeight-safeBottom+100+'px'}">
			<view class="chat-main">
				<view class="chat-ls" v-for="(item,index) in unshiftmsg" :key="index" :id="'msg'+ index">
					<view class="chat-time" v-if="item.createTime != ''">{{changeTime(item.createTime)}}</view>
					<view class="msg-m msg-left" v-if="!item.isMine">
						<view class="message">
							<view @longpress="copy(item.sendText)" class="msg-text">
								<text>{{item.sendText.replace(/\\n/g,'\n') || '思考中💭'}}</text>
							</view>
						</view>
					</view>
					<view class="msg-m msg-right" v-else>
						<view class="message">
							<view class="msg-text">{{item.sendText}}</view>
						</view>
					</view>
				</view>
			</view>
			<p id="bottom"></p>
		</scroll-view>
		<submit @blur="hideBorad" :keyboardHeight="keyboardHeight" @inputs="inputs" :isLoading="loading"
			:dialogCount="dialogCount">
		</submit>
	</view>
</template>

<script>
	import dateTime from './dateTime.js';
	import submit from './submit.vue'
	const {
		Base64
	} = require('../../../utils/baseutf.js')
	export default {
		data() {
			return {
				title: 'AI法律解答',
				msg: [{
					"isMine": false,
					"sendText": '你好！请输入您的问题，我来为您解答。',
					"createTime": new Date(),
					"updateTime": null,
					"chatmState": 1,
				}],
				// 反转数据接收
				unshiftmsg: [],
				scrollToView: '',
				oldTime: new Date(),
				chatType: 1,
				message: '',
				dialogCount: 0,
				loading: false,
				textContent: '',
				contentIndex: 0,
				requestTask: null,
				keyboardHeight: 0,
				safeBottom: 0,
				inputType: false
			}
		},
		onPageScroll(res) {
			if (this.keyboardHeight) {
				uni.hideKeyboard()
			}
		},
		onLoad(e) {
			let that = this
			uni.getSystemInfo({
				success: function(res) {
					console.log(res)
					// 获取安全区域的底部高度
					that.safeBottom = res.safeAreaInsets.bottom;
					console.log('安全区域底部高度：' + that.safeBottom + 'px');
				}
			});
			if (e.name) {
				uni.setNavigationBarTitle({
					title: e.name
				})
			}
			uni.onKeyboardHeightChange((res) => {
				console.log(res);
				if (res.height) {
					setTimeout(()=>{
						this.keyboardHeight = res.height; // 设置键盘高度
					},100)
					// this.goBottom()
				} else {
					uni.hideKeyboard();
					this.keyboardHeight = 0; // 键盘收起时重置高度
				}

			});
		},
		onReady() {

			this.dialogCount = uni.getStorageSync('dialogCount') || 0
			// 数组倒叙 主要是应对后端传过来的数据
			for (var i = 0; i < this.msg.length; i++) {
				//时间间隔处理
				if (i < this.msg.length - 1) { //这里表示头部时间还是显示一下
					let t = dateTime.spaceTime(this.oldTime, this.msg[i].createTime);
					if (t) {
						this.oldTime = t;
					}
					this.msg[i].createTime = t;
				}
				this.unshiftmsg.unshift(this.msg[i]);
			}

		},

		// 页面销毁
		onUnload() {
			let list = uni.getStorageSync('dialogRecord') || []
			if (this.unshiftmsg.length > 1) {
				list.unshift(this.unshiftmsg)
				uni.setStorageSync('dialogRecord', list)
			}
			if (this.requestTask) this.requestTask.abort()
			clearTimeout()
			uni.setStorageSync('dialogCount', this.dialogCount)
		},
		components: {
			submit,
		},
		methods: {
			changeTime(date) {
				return dateTime.dateTime1(date);
			},
			hideBorad() {
				this.showKeyNum = 2;
				this.keyboardHeight = 0;
			},
			touchstart(){
					uni.hideKeyboard()
			},
			//接受输入内容
			inputs(e) {

				if (this.loading) return
				//时间间隔处理
				this.message = e.message
				let data = {
					"isMine": true,
					"sendText": e.message,
					"createTime": '',
					"updateTime": '',
					"chatmState": 1,
				};
				this.unshiftmsg.push(data);
				// 跳转到最后一条数据 与前面的:id进行对照
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})
				setTimeout(() => {
					this.aiPush()
				}, 500)
			},
			// 新加一条AI消息
			aiPush() {
				let data = {
					"isMine": false,
					"sendText": '',
					"createTime": '',
					"updateTime": '',
					"chatmState": 1,
				};
				if (this.requestTask) this.requestTask.abort()
				this.textContent = ''
				this.contentIndex = 0
				this.unshiftmsg.push(data);
				clearTimeout()
				this.bindChunkTest()
				this.$nextTick(() => {
					// 滚动到底部
					let chat = uni.createSelectorQuery().select('#chat');
					chat.boundingClientRect((rect) => {
						console.log(rect)
						uni.pageScrollTo({
							scrollTop: rect.height,
							duration: 0
						});
					}).exec();
				});
			},
			// 请求AI接口
			bindChunkTest() {
				this.dialogCount++
				let that = this
				// #ifdef MP
				this.requestTask = wx.request({
					url: 'https://lawyer.yic3.cn/api/chat/stream',
					timeout: 30000,
					responseType: 'text',
					method: 'POST',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'x-app-id': '10026',
						'x-token': uni.getStorageSync('Token'),
					},
					enableChunked: true,
					data: {
						chatType: this.chatType,
						question: this.message,
					},
					success(res) {
						// console.log(res)
					}
				});
				this.requestTask.onChunkReceived(function(response) {
					const arrayBuffer = response.data;
					const uint8Array = new Uint8Array(arrayBuffer);
					let text = wx.arrayBufferToBase64(uint8Array);

					text = Base64.decode(text);
					let a = text.split(',')[2].split('"')[3];
					// a = a.replace(/\\n/g, '<br>')
					console.log(a)

					if (a) {
						let lastIndex = that.unshiftmsg.length - 1 // 信息数组最后一个的索引
						that.textContent = that.textContent + a
						let timer
						const addCharToB = () => {
							if (that.contentIndex < that.textContent.length && !that.unshiftmsg[lastIndex]
								.isMine) {
								that.unshiftmsg[lastIndex].sendText += that.textContent
									.charAt(that.contentIndex);
								that.contentIndex++;
								if (timer) timer = null
								timer = setTimeout(addCharToB, 10);
								// that.$nextTick(() => {
								// 	// 滚动到底部
								// 	let chat = uni.createSelectorQuery().select('#chat');
								// 	chat.boundingClientRect((rect) => {
								// 		console.log(rect)
								// 		uni.pageScrollTo({
								// 			scrollTop: rect.height,
								// 			duration: 0
								// 		});
								// 	}).exec();
								// });
							}
						};
						addCharToB();
					}

				}, )
				// #endif
				// #ifdef APP || APP-PLUS
				this.loading = true
				this.$api.chat({
					chatType: 1,
					question: this.message,
					isNewChat: 1,
				}).then(res => {
					this.loading = false
					console.log(res)
					let lastIndex = that.unshiftmsg.length - 1 // 信息数组最后一个的索引
					let index = 0
					let timer
					const addCharToB = () => {
						if (index < res.data.data.answer.length && !that.unshiftmsg[lastIndex]
							.isMine) {
							that.unshiftmsg[lastIndex].sendText += res.data.data.answer
								.charAt(index);
							index++;
							if (timer) timer = null
							timer = setTimeout(addCharToB, 50);
						}
					};
					addCharToB();
				})
				// #endif

			},
			// 复制文字
			copy(text) {
				uni.setClipboardData({
					data: text,
					success() {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						})
					}
				})
			},
			chatStream(question) {
				this.$api.chatStream({
					chatType: this.chatType,
					question,
				}).then(res => {
					that.unshiftmsg[that.unshiftmsg.length - 1].sendText = res.data.data.answer
					console.log(res)
				})
			},
			// 滚动到底部
			goBottom() {
				this.scrollToView = '';
				this.$nextTick(() => {
					// 滚动到底部
					let chat = uni.createSelectorQuery().select('#chat');
					chat.boundingClientRect((rect) => {
						uni.pageScrollTo({
							scrollTop: rect.height,
							duration: 0
						});
					}).exec();
				});
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})
			}
		}
	}
</script>
<style lang="scss">
	@import 'dialog.scss'
</style>